package com.googlecode.jexnihilo;

import com.googlecode.totallylazy.Callable1;
import com.googlecode.totallylazy.Sequence;
import com.googlecode.totallylazy.Sources;

import java.io.IOException;

public class RenamingSource implements Sources {
	private final Sources decorated;
	private final String oldPath;
	private final String newPath;

	public RenamingSource(Sources decorated, String oldPath, String newPath) {
		this.decorated = decorated;
		this.oldPath = oldPath;
		this.newPath = newPath;
	}

	static Sources renameSources(final Sources decorated, String oldPath, String newPath) {
		return new RenamingSource(decorated, oldPath, newPath);
	}

	@Override
	public Sequence<Source> sources() {
		return decorated.sources().map(rename());
	}

	private Callable1<? super Source, ? extends Source> rename() {
		return new Callable1<Source, Source>() {
			@Override
			public Source call(Source source) throws Exception {
				if(!source.name.contains(oldPath)) return source;
				return new Source(
						source.name.replace(oldPath, newPath),
						source.modified,
						source.input);
			}
		};
	}

	@Override
	public void close() throws IOException {
		decorated.close();
	}
}
